<template>
  <div class="container">
    <!-- 过滤器 -->
    <el-card shadow="always" class="filter-card">
      <h1 class="title" style="margin-top: -5px">408习题训练</h1>
      
      <!-- 使用单独的容器包装筛选条件和按钮 -->
      <div class="filter-wrapper">
        <el-form :inline="true" :model="filters" class="filter-form">
          <el-form-item label="题目类型">
            <el-select v-model="filters.type" clearable placeholder="选择题目类型" @change="fetchQuestions" style="width: 200px;">
              <el-option label="选择题" :value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="科目">
            <el-select v-model="filters.subject" clearable placeholder="选择科目" @change="fetchQuestions" style="width: 200px;">
              <el-option label="数据结构" :value="1"></el-option>
              <el-option label="操作系统" :value="2"></el-option>
              <el-option label="计算机网络" :value="3"></el-option>
              <el-option label="计算机组成原理" :value="4"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="年份">
            <el-select v-model="filters.year" clearable placeholder="选择年份" @change="fetchQuestions" style="width: 200px;">
              <el-option v-for="year in years" :key="year" :label="year" :value="year"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        
        <!-- 按钮区域完全独立出来 -->
        <div class="button-group mt-4 flex justify-center">
          <el-button @click="resetFilters">重置</el-button>
          <el-button type="primary" @click="fetchQuestions" class="ml-3">应用过滤器</el-button>
        </div>
      </div>
    </el-card>

    <!-- 登录提示 -->
    <el-alert v-if="!token && !loading" title="请先登录以访问题目" type="warning" show-icon closable @close="tokenWarning = false" class="error-alert"></el-alert>

    <!-- 加载状态 -->
    <div v-loading="loading" class="loading-container">
      <el-empty v-if="!loading && !error && !questions.length && token" description="未找到符合条件的题目，请检查过滤条件或数据库！">
        <el-button type="primary" @click="resetFilters">重置过滤器</el-button>
      </el-empty>
    </div>

    <!-- 错误提示 -->
    <el-alert v-if="error" :title="error" type="error" show-icon closable @close="error = null" class="error-alert"></el-alert>

    <!-- 题目列表 -->
    <div v-if="questions.length && !loading" class="question-list">
      <el-card v-for="(question, index) in questions" :key="question.questionId || 'temp-' + index" shadow="hover" class="question-card">
        <div class="question-header">
          <div class="question-meta">
            <span class="question-id">Question ID: {{ question.questionId || 'Missing questionId' }}</span>
            <span v-if="question.subject" class="question-subject">| {{ getSubjectName(question.subject) }}</span>
          </div>
        </div>
        <div class="question-content">
          <pre class="question-stem">{{ getQuestionStem(question.content) }}</pre>
          <div v-if="question.type === 1" class="options">
            <el-radio-group v-model="selectedAnswers[question.questionId || 'temp-' + index]">
              <el-radio
                v-for="(option, optionIndex) in parseOptions(question.content)"
                :key="optionIndex"
                :value="option.label"
                :label="`${option.label}. ${option.text}`"
                class="option-item"
              >
                {{ option.label }}. {{ option.text }}
              </el-radio>
            </el-radio-group>
          </div>
          <div v-else>
            <el-input v-model="selectedAnswers[question.questionId || 'temp-' + index]" placeholder="请输入答案" class="answer-input"></el-input>
          </div>
        </div>
        <div class="actions">
          <el-button type="text" @click="toggleAnswer(question.questionId || 'temp-' + index)">
            {{ showAnswers[question.questionId || 'temp-' + index] ? '隐藏答案与解析' : '显示答案与解析' }}
          </el-button>
          <el-button v-if="question.type === 1 && selectedAnswers[question.questionId || 'temp-' + index]" type="text" @click="checkAnswer(question)">
            检查答案
          </el-button>
          <el-button type="text" @click="toggleFavorite(question)">
            {{ isFavorite(question.questionId) ? '已收藏' : '收藏' }}
          </el-button>
        </div>
        <el-collapse-transition>
          <div v-if="showAnswers[question.questionId || 'temp-' + index]" class="answer-analysis">
            <div class="answer-box">
              <p><strong>答案：</strong> {{ question.answer }}</p>
            </div>
            <div class="analysis-box">
              <p><strong>解析：</strong> {{ question.analysis }}</p>
            </div>
          </div>
        </el-collapse-transition>
        <el-alert v-if="answerFeedback[question.questionId || 'temp-' + index]" :title="answerFeedback[question.questionId || 'temp-' + index].message"
                  :type="answerFeedback[question.questionId || 'temp-' + index].correct ? 'success' : 'error'" show-icon closable
                  @close="deleteFeedback(question.questionId || 'temp-' + index)" class="feedback-alert">
        </el-alert>
      </el-card>
    </div>

    <!-- 分页 -->
    <el-pagination v-if="total > 0 && !loading" layout="prev, pager, next, jumper" v-model:current-page="pageNum"
                   :page-size="pageSize" :total="total" @current-change="fetchQuestions" class="pagination">
    </el-pagination>
  </div>
</template>

<script>
import { defineComponent, ref, watch, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import useUserInfoStore from '@/stores/userInfo.js';

export default defineComponent({
  name: 'PersonalizedExercises',
  setup() {
    const userInfoStore = useUserInfoStore();
    const filters = ref({
      type: null,
      subject: null,
      year: null,
    });
    const pageNum = ref(1);
    const pageSize = ref(10);
    const total = ref(0);
    const questions = ref([]);
    const selectedAnswers = ref({});
    const showAnswers = ref({});
    const answerFeedback = ref({});
    const years = Array.from({ length: 2019 - 2017 + 1 }, (_, i) => 2017 + i);
    const loading = ref(false);
    const error = ref(null);
    const token = ref(localStorage.getItem('token') || null);
    const tokenWarning = ref(true);
    
    // 所有科目的收藏题目
    const favorites = ref([]);

    // 科目名称映射函数
    const getSubjectName = (subjectId) => {
      const subjectMap = {
        1: '数据结构',
        2: '操作系统',
        3: '计算机网络',
        4: '计算机组成原理'
      };
      return subjectMap[subjectId] || `科目 ${subjectId}`;
    };

    const fetchQuestions = async () => {
      if (!token.value) {
        error.value = '请先登录以获取题目';
        loading.value = false;
        ElMessage.error(error.value);
        return;
      }

      loading.value = true;
      error.value = null;
      try {
        const response = await axios.get('http://localhost:8080/question/filter', {
          params: {
            type: filters.value.type ?? undefined,
            subject: filters.value.subject ?? undefined,
            year: filters.value.year ?? undefined,
            pageNum: pageNum.value,
            pageSize: pageSize.value,
          },
          headers: {
            Authorization: `Bearer eyJhbGciOiJIUzI1NiJ9.eyJwaG9uZSI6IjEzODAwMTM4MDAxIiwiaWQiOjEsImlhdCI6MTc0OTkxMzk5OSwiZXhwIjoxNzUwMjU5NTk5fQ.bmvoB0J0jHNaB541HO_r7kRNs179VGknr6ADt9EdMKg`,
          },
        });
        if (response.data.code === 0) {
          const newQuestions = response.data.data?.list || [];
          questions.value = newQuestions;
          total.value = response.data.data?.total || 0;
          pageNum.value = response.data.data?.pageNum || 1;
        } else {
          error.value = response.data.msg || '获取题目失败，请稍后重试';
          ElMessage.error(error.value);
        }
      } catch (error) {
        console.error('API Error Details:', {
          message: error.message,
          code: error.code,
          response: error.response ? {
            status: error.response.status,
            data: error.response.data,
            headers: error.response.headers,
          } : null,
        });
        if (error.response?.status === 401) {
          error.value = '认证失败：无效或过期的 token，请重新登录';
          token.value = null;
          localStorage.removeItem('token');
        } else if (error.response?.status === 404) {
          error.value = 'API 端点不存在，请确保后端服务运行在 http://localhost:8080/question/filter';
        } else {
          error.value = '无法连接到后端服务，请检查网络、CORS设置或后端服务状态';
        }
        ElMessage.error(error.value);
      } finally {
        loading.value = false;
      }
    };

    const getQuestionStem = (content) => {
      if (!content) return '无题干';
      const lines = content.split('\n');
      const optionRegex = /^[A-D]\.\s*(.*)$/;
      const stemLines = lines.filter(line => !optionRegex.test(line.trim()));
      return stemLines.join('\n').trim() || '无题干';
    };

    const parseOptions = (content) => {
      const lines = content?.split('\n') || [];
      const optionRegex = /^[A-D]\.\s*(.*)$/;
      const options = [];
      for (const line of lines) {
        const match = line.match(optionRegex);
        if (match) {
          options.push({ label: match[0][0], text: match[1].trim() });
        }
      }
      return options;
    };

    const toggleAnswer = (questionId) => {
      showAnswers.value[questionId] = !showAnswers.value[questionId];
    };

    const checkAnswer = (question) => {
      const questionId = question.questionId || 'temp-' + question.index;
      const userAnswer = selectedAnswers.value[questionId];
      const correctAnswer = question.answer;
      const isCorrect = userAnswer === correctAnswer;
      answerFeedback.value[questionId] = {
        correct: isCorrect,
        message: isCorrect ? '回答正确！' : `回答错误，正确答案是 ${correctAnswer}`,
      };
      ElMessage({
        message: isCorrect ? '回答正确！' : '回答错误，请查看解析！',
        type: isCorrect ? 'success' : 'error',
      });
    };

    const deleteFeedback = (questionId) => {
      delete answerFeedback.value[questionId];
    };

    const resetFilters = () => {
      filters.value = { type: null, subject: null, year: null };
      pageNum.value = 1;
      fetchQuestions();
    };

    // 获取所有科目的收藏题目（串行请求）
    const fetchAllFavorites = async () => {
      if (!token.value) return;
      try {
        // 首先获取用户的所有错题本信息
        const bookResponse = await axios.get('http://localhost:8080/errorbook/selectByUserId', {
          params: {
            userId: userInfoStore.userId || 1, // 动态获取
          },
          headers: {
            Authorization: `Bearer eyJhbGciOiJIUzI1NiJ9.eyJwaG9uZSI6IjEzODAwMTM4MDAxIiwiaWQiOjEsImlhdCI6MTc0OTkxMzk5OSwiZXhwIjoxNzUwMjU5NTk5fQ.bmvoB0J0jHNaB541HO_r7kRNs179VGknr6ADt9EdMKg`,
          },
        });

        if (bookResponse.data.code === 0) {
          const bookList = bookResponse.data.data || [];
          console.log('获取错题本列表成功:', bookList);
          
          const allRecords = [];
          
          // 串行获取每个错题本的题目
          for (const book of bookList) {
            try {
              console.log(`正在获取错题本 ${book.bookId} (${book.bookName || '未知科目'}) 的错题记录`);
              const recordResponse = await axios.get('http://localhost:8080/errorbook/selectAllRecord', {
                params: {
                  bookId: book.bookId,
                  pageNum: 1,
                  pageSize: 100, // 获取足够多的记录
                },
                headers: {
                  Authorization: `Bearer ${token.value}`,
                },
              });
              
              if (recordResponse.data.code === 0) {
                const records = recordResponse.data.data?.list || [];
                console.log(`成功获取错题本 ${book.bookId} 的 ${records.length} 条记录`);
                allRecords.push(...records);
              } else {
                console.error(`获取错题本 ${book.bookId} 的错题记录失败:`, recordResponse.data.msg);
              }
            } catch (error) {
              console.error(`获取错题本 ${book.bookId} 的错题记录时发生异常:`, error);
            }
          }
          
          // 更新收藏列表
          favorites.value = allRecords;
          console.log('成功获取所有收藏题目，共', allRecords.length, '条');
        } else {
          ElMessage.error(bookResponse.data.msg || '获取错题本失败，请稍后重试');
        }
      } catch (error) {
        console.error('获取收藏题目失败:', error);
        ElMessage.error('获取收藏题目失败，请稍后重试');
      }
    };

    // 判断题目是否已收藏（检查所有科目）
    const isFavorite = (questionId) => {
      if (!questionId) return false;
      return favorites.value.some(favorite => favorite.questionId === questionId);
    };

    const toggleFavorite = async (question) => {
      if (!token.value) {
        ElMessage.error('请先登录以使用收藏功能');
        return;
      }
      const questionId = question.questionId;
      if (!questionId) {
        ElMessage.error('题目ID无效，无法收藏');
        return;
      }

      // 根据题目的科目动态设置 bookId
      const subjectToBookIdMap = {
        1: 1, // 数据结构 → 错题本1
        2: 2, // 操作系统 → 错题本2
        3: 3, // 计算机网络 → 错题本3
        4: 4, // 计算机组成原理 → 错题本4
      };
      const bookId = subjectToBookIdMap[question.subject] || 1; // 默认为数据结构

      if (isFavorite(questionId)) {
        // 取消收藏
        try {
          const favorite = favorites.value.find(fav => fav.questionId === questionId);
          if (!favorite || !favorite.recordId) {
            ElMessage.error('错题记录无效，无法取消收藏');
            return;
          }
          
          const response = await axios.post('http://localhost:8080/errorbook/deleteRecord', {
            recordId: favorite.recordId,
          }, {
            headers: {
              Authorization: `Bearer eyJhbGciOiJIUzI1NiJ9.eyJwaG9uZSI6IjEzODAwMTM4MDAxIiwiaWQiOjEsImlhdCI6MTc0OTkxMzk5OSwiZXhwIjoxNzUwMjU5NTk5fQ.bmvoB0J0jHNaB541HO_r7kRNs179VGknr6ADt9EdMKg`,
            },
          });
          
          if (response.data.code === 0) {
            ElMessage.success('取消收藏成功');
            await fetchAllFavorites(); // 更新收藏列表
          } else {
            ElMessage.error(response.data.msg || '已收藏');
          }
        } catch (error) {
          console.error('取消收藏失败:', error);
          ElMessage.error('已收藏');
        }
      } else {
        // 添加收藏
        try {
          const response = await axios.post('http://localhost:8080/errorbook/insertRecord', {
            bookId: bookId,
            questionId: questionId,
          }, {
            headers: {
              Authorization: `Bearer ${token.value}`,
            },
          });
          
          if (response.data.code === 0) {
            ElMessage.success('收藏成功');
            await fetchAllFavorites(); // 更新收藏列表
          } else {
            ElMessage.error(response.data.msg || '收藏失败，请稍后重试');
          }
        } catch (error) {
          console.error('收藏失败:', error);
          ElMessage.error('收藏失败，请稍后重试');
        }
      }
    };

    // 监听token变化，更新数据
    watch(token, (newToken) => {
      if (newToken) {
        fetchQuestions();
        fetchAllFavorites();
      }
    });

    // 组件挂载时初始化
    onMounted(() => {
      fetchQuestions();
      fetchAllFavorites();
    });

    return {
      filters,
      pageNum,
      pageSize,
      total,
      questions,
      selectedAnswers,
      showAnswers,
      answerFeedback,
      years,
      loading,
      error,
      token,
      tokenWarning,
      fetchQuestions,
      getQuestionStem,
      parseOptions,
      toggleAnswer,
      checkAnswer,
      deleteFeedback,
      resetFilters,
      isFavorite,
      toggleFavorite,
      getSubjectName,
    };
  },
});
</script>

<style scoped lang="scss">
/* 定义现代配色方案 */
$primary-color: #409EFF;
$secondary-color: #67C23A;
$accent-color: #E6A23C;
$warning-color: #E6A23C;
$error-color: #F56C6C;
$info-color: #909399;
$bg-color: #F5F7FA;
$card-bg: #FFFFFF;
$text-color: #303133;
$text-secondary: #606266;
$border-color: #DCDFE6;

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background-color: $bg-color;
  min-height: 100vh;
}

.title {
  font-size: 32px;
  font-weight: 700;
  color: $text-color;
  text-align: center;
  margin-bottom: 20px;
  background: linear-gradient(to right, $primary-color, $secondary-color);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.filter-card {
  background-color: $card-bg;
  color: $text-color;
  margin-bottom: 20px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.filter-card:hover {
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
}

.filter-wrapper {
  padding: 15px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  justify-content: center; /* 表单整体居中 */
}

.button-group {
  display: flex;
  justify-content: center;
}

.el-form-item__label {
  font-weight: 500;
  color: $text-color;
}

.loading-container {
  min-height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.error-alert {
  margin-bottom: 20px;
  border-radius: 8px;
}

.question-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.question-card {
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
  background-color: $card-bg;
}

.question-card:hover {
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.question-header {
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid $border-color;
}

.question-meta {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: $text-secondary;
}

.question-id {
  font-weight: 500;
  color: $text-color;
  margin-right: 10px;
}

.question-subject {
  background-color: rgba(64, 158, 255, 0.1);
  color: $primary-color;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 13px;
  margin-left: 8px;
}

.question-stem {
  font-size: 16px;
  font-weight: 500;
  color: $text-color;
  margin-bottom: 16px;
  white-space: pre-wrap;
  line-height: 1.6;
  padding: 12px;
  background-color: rgba(245, 247, 250, 0.8);
  border-radius: 8px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.options {
  margin-bottom: 16px;
}

.option-item {
  display: block;
  margin-bottom: 12px;
  padding: 8px 12px;
  border-radius: 6px;
  transition: all 0.2s ease;
}

.option-item:hover {
  background-color: rgba(64, 158, 255, 0.05);
}

.answer-input {
  width: 100%;
  max-width: 400px;
}

.actions {
  margin-top: 16px;
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

.answer-analysis {
  margin-top: 16px;
  padding: 16px;
  background-color: rgba(245, 247, 250, 0.8);
  border-radius: 8px;
  border-left: 4px solid $primary-color;
}

.answer-box, .analysis-box {
  margin-bottom: 12px;
}

.answer-box p {
  font-weight: 500;
  color: $text-color;
}

.analysis-box p {
  color: $text-secondary;
  line-height: 1.6;
}

.feedback-alert {
  margin-top: 16px;
  border-radius: 8px;
}

.pagination {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .container {
    padding: 12px;
  }
  
  .title {
    font-size: 24px;
  }
  
  .filter-card {
    margin-left: 0;
  }
  
  .filter-form {
    gap: 10px;
    flex-direction: column; /* 小屏幕下垂直排列 */
    align-items: center; /* 子元素居中 */
  }
  
  .question-card {
    padding: 16px;
  }
  
  .question-stem {
    font-size: 15px;
    padding: 10px;
  }
}
</style>